import { ref, unref, onMounted } from 'vue';
import { useForm } from '/@/components/Form/index';
import { FormSchema } from '/@/components/Table';
import { getConfigByKey, getSensitiveConfig as getSensitiveConfigApi } from '/@/views/system/config/config.api';
import { ConfigKeyItem } from '/@/views/system/config/config.model';
import { useMessage } from '/@/hooks/web/useMessage';
import { defHttp } from '/@/utils/http/axios';
import { useLoading } from '/@/components/Loading';
import { useEmitter } from '/@/store/modules/user';
export interface ConfigModel {
  id?: string;
  configValue: string;
  tenantId: string;
  isSensitive: boolean
}

export interface ConfigFormProps {
  configKey: ConfigKeyItem;
  schemas: FormSchema[];
  labelWidth?: number;
  handleSubmitBefore? : Function;
  // 表单字段值发生改变
  fieldValueChange? : Function;
  formOption?: Object
}

export const useConfigForm = (props : ConfigFormProps, emit?: EmitType) => {
  console.log('props', props);
  const { createMessage } = useMessage();
  const loading = ref(false);
  // 是否为敏感的
  const isSensitive = ref(false);
  const record = ref<ConfigModel>({
    configValue: '{}',
    tenantId: '-1',
    isSensitive: false
  })
  const queryLoading = ref()

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, appendSchemaByField, removeSchemaByField, getFieldsValue }] = useForm({
    schemas: props.schemas,
    showActionButtonGroup: false,
    showSubmitButton: true,
    showResetButton: true,
    labelWidth: props.labelWidth || 100,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    ...props.formOption
  });


  onMounted(async () => {
    queryLoading.value = true

    try {
      // 重置表单
      await resetFields();
      record.value = await getConfigByKey(props.configKey.code)
      isSensitive.value = record.value.isSensitive
      handleFieldsValue()
    } finally {
      queryLoading.value = false
      emit && emit('query-success')
    }
  })

  const handleFieldsValue = async () => {
    const configValue = record.value.configValue
    const jsonConfigValue = configValue && configValue !== '' ? JSON.parse(configValue) : {}
    const tenantId = record.value.tenantId
    //表单赋值
    await setFieldsValue({
      tenantId, ...jsonConfigValue,
    });
    props.fieldValueChange && props.fieldValueChange(jsonConfigValue)
    
  }

  //表单提交事件
  const handleSubmit = async () => {
    try {
      loading.value = true
      let values = await validate()
      console.log('values: ', values)
      props?.handleSubmitBefore && props.handleSubmitBefore(values)
      //提交表单
      await defHttp.post({url: props.configKey.api, params: {
        id: record.value.id, 
        configKey: props.configKey.code, 
        configName: props.configKey.code, 
        configValue: JSON.stringify(values)
      }});
      record.value = await getConfigByKey(props.configKey.code)
      handleFieldsValue()
      createMessage.success(`编辑成功`)
    } finally {
      loading.value = false
    }
  }

  /**
   * 处理敏感配置信息
   * @param validateInfo 来自验证组件结果
   */
  const handleSensitiveConfig = async (validateInfo) => {
    try {
      console.log('validateInfo', validateInfo);
      record.value = await getSensitiveConfigApi({...validateInfo, configKey: props.configKey.code})
      isSensitive.value = record.value.isSensitive
      handleFieldsValue()
    } finally {
      
    }
  }
  return {
    handleSubmit, resetFields, validate, registerForm, handleSensitiveConfig, 
    getFieldsValue,
    appendSchemaByField, removeSchemaByField, setFieldsValue, queryLoading,
    loading, isSensitive
  }
}